package com.smart.business.controller;

import com.github.pagehelper.PageInfo;
import com.smart.aop.log.LogType;
import com.smart.aop.log.SaveLog;
import com.smart.aop.permission.HasPermission;
import com.smart.business.dao.MeterTypeDao;
import com.smart.common.annotation.PermissionCheck;
import com.smart.common.utils.DateUtil;
import com.smart.entity.business.*;
import com.smart.model.excel.annotation.ExcelField;
import com.smart.model.exception.SmartException;
import com.smart.model.response.r.Result;
import com.smart.model.response.r.ResultCode;
import com.smart.model.response.r.ResultWrapper;
import com.smart.service.business.ParameterTemplateService;
import com.smart.service.business.PointService;
import com.smart.tools.excel.ExcelExport;
import com.smart.tools.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 点位配置 Controller
 *
 * @author wf
 * @since 2025-07-14 10:43:13
 */
@RestController
@RequestMapping("/business/point")
public class PointController {
    @Autowired
    PointService pointService;
    @Autowired
    ResultWrapper resultWrapper;
    @Autowired
    MeterTypeDao meterTypeDao;

    @Autowired
    ParameterTemplateService parameterTemplateService;

    /**
     * 列表
     *
     * @param pointEntity 点位配置bean
     * @return String
     */
    @GetMapping("/page")
    public String page(PointEntity pointEntity) {
        return Result.data(pointService.findPage(pointEntity));
    }

    /**
     * 列表（不分页）
     *
     * @param pointEntity 点位配置bean
     * @return String
     */
    @GetMapping("/list")
    public String list(PointEntity pointEntity) {
        return Result.data(pointService.findList(pointEntity));
    }

    /**
     * 信息
     *
     * @param id 主键ID
     * @return String
     */
    @GetMapping("/get")
    public String get(@RequestParam String id) {
        PointEntity result = pointService.get(id);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 保存
     *
     * @param pointEntity 点位配置bean
     * @return String
     */
    @HasPermission("point:add")
    @PostMapping("/save")
    @SaveLog(module = "点位配置管理" , type = LogType.ADD)
    @PermissionCheck
    public String save(@RequestBody PointEntity pointEntity) {
        PointEntity result = pointService.savePoint(pointEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 修改
     *
     * @param pointEntity 点位配置bean
     * @return String
     */
    @HasPermission("point:update")
    @PostMapping("/update")
    @SaveLog(module = "点位配置管理" , type = LogType.UPDATE)
    public String update(@RequestBody PointEntity pointEntity) {
        pointEntity.setMeterTypeId(meterTypeDao.selectByName(pointEntity.getMeterTypeId()));
        if(pointEntity.getMeterTypeId() == null){
            return Result.fail("能源类型不存在");
        }
        if(pointEntity.getCollectorId() != null){
            return Result.fail("请断开连接再进行修改");
        }
        PointEntity result = pointService.updateEntity(pointEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 删除
     *
     * @param requestBody 主键ID
     * @return String
     */
    @HasPermission("point:delete")
    @PostMapping("/delete")
    @SaveLog(module = "点位配置管理", type = LogType.DELETE)
    public String delete(@RequestBody Map<String, List<String>> requestBody) {
        List<String> deleteIds = requestBody.get("deleteIds");
        if (deleteIds != null && !deleteIds.isEmpty()) {
            return Result.status(pointService.deletePoints(deleteIds));
        }
        return Result.fail("未提供有效点位ID");
    }

    /**
     * 导出
     *
     * @param pointEntity 点位配置bean
     * @param response 响应
     */
    @HasPermission("point:export")
    @PostMapping(value = "/export")
    public void exportData(@RequestBody PointEntity pointEntity, HttpServletResponse response) {
        List<PointEntity> list = resultWrapper.setListIdentityInfo(pointService.findList(pointEntity), PointEntity.class);
        String fileName = "点位配置数据" + DateUtil.getDate("yyyyMMddHHmmss") + ".xlsx";
        try (ExcelExport export = new ExcelExport("点位配置数据", PointEntity.class)) {
            export.setDataList(list).write(response, fileName);
        }
    }

    /**
     * 导入
     *
     * @param request 请求
     */
    @HasPermission("point:import")
    @PostMapping(value = "/import")
    public String importData(MultipartHttpServletRequest request) {
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        List<MultipartFile> files = multiFileMap.get("files");
        try (ExcelImport excelImport = new ExcelImport(files.get(0), 2, 0)) {
            List<PointEntity> dataList = excelImport.getDataList(PointEntity.class);
            return Result.status(pointService.saveBatch(dataList));
        } catch (Exception e) {
            return Result.fail("导入失败！");
        }
    }

    /**
     * 下载导入模板
     *
     * @param response 响应
     */
    @GetMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "导入点位配置模板.xlsx";
        try (ExcelExport export = new ExcelExport("点位配置数据", PointEntity.class, null, ExcelField.Type.IMPORT)) {
            export.write(response, fileName);
        }
    }

    @PermissionCheck
    @GetMapping("/getPointList")
    public String getPointList(@RequestParam(required = false) String id,
                               @RequestParam(required = false) String name,
                               @RequestParam(required = false) String meterTypeId,
                               @RequestParam(required = false) String code,
                               @RequestParam(defaultValue = "1") int current,
                               @RequestParam(defaultValue = "10") int size) {
        List<PointEntity> list = pointService.getPointList(id, meterTypeId, name, code, current, size);
        PageInfo<PointEntity> pageInfo = new PageInfo<>(list);
        return Result.data(pageInfo);
    }

    /**
     * 获取未连接的采集器编号列表
     *
     * @return 未连接的采集器编号列表
     */
    @PermissionCheck
    @GetMapping("/unConnectCollector")
    public String unConnectCollector() {
        List<CollectorEntity> collector = pointService.unConnectCollector();
        return Result.data(collector);
    }

    @GetMapping("/templateList")
    public String templateList(@RequestParam String meterTypeId) {
        meterTypeId = meterTypeDao.selectByName(meterTypeId);
        if (meterTypeId == null)
            return Result.fail("能源类型不存在");
        List<ParameterTemplateEntity> list = parameterTemplateService.templateList(meterTypeId);
        return Result.data(list);
    }

    /**
     * 定义点位连接状态
     * requestBody  ConnectDTO 链接实体
     * @return String
     */
    @PostMapping("/setConnectStatus")
    @SaveLog(module = "点位管理" , type = LogType.UPDATE)
    public String setConnectStatus(@RequestBody ConnectDTO connectDTO) {
        PointEntity result = pointService.setConnectStatus(connectDTO);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 获取采集器未连接的通道号
     * @param collectorId 采集器id
     */
    @GetMapping("/getUnConnectChannels")
    public String getUnConnectChannels(@RequestParam String collectorId) {
        return Result.data(pointService.getUnConnectChannels(collectorId));
    }


    /**
     * 断开点位连接
     * @param request 请求体对象
     * @return String
     */
    @PostMapping("/disConnect")
    public String disConnect(@RequestBody Map<String, String> request) {
        String result = pointService.disConnect(request.get("id"));
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 设置点位是否禁用
     * @param request 请求体对象
     * @return  String
     */

    @PostMapping("/setDisable")
    public String setDisable(@RequestBody Map<String,Object> request) {
        String pointId = (String) request.get("pointId");
        Integer isDisable = (Integer) request.get("isDisable");
        if (pointId == null || isDisable == null) {
            throw new SmartException("参数不完整");
        }
        PointEntity result = pointService.setDisable(pointId, isDisable);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 获取历史数据列表
     *
     * @param  pointId 点位id
     * @return String
     */
    @PermissionCheck
    @GetMapping("/getList")
    public String getList(@RequestParam(required = false) String pointId,
                          @RequestParam(required = false) String startTime,
                          @RequestParam(required = false) String endTime,
                          @RequestParam(required = false) String frequency,
                          @RequestParam(defaultValue = "1") int current,
                          @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> map = pointService.getList(pointId, startTime, endTime, frequency, current, size);
        return Result.data(map);
    }
    /**
     * 实时状态数据
     * @return String
     */
    @PermissionCheck
    @GetMapping("/getPointMessage")
    public String getPointMessage() {
        return Result.data(pointService.getPointMessage());
    }

    /**
     * 获取状态数据
     */
    @PermissionCheck
    @GetMapping("/getBarChartData")
    public String getBarChartData(@RequestParam String meterTypeId,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime) {
        return Result.data(pointService.getBarChartData(meterTypeId,startTime, endTime));
    }

    /**
     * 仪表盘各时间段消耗值展示
     *
     */
    @PermissionCheck
    @GetMapping("/getTimeConsumption")
    public String getTimeConsumption(@RequestParam String meterTypeId) {
        Map<String, Object> result = pointService.getTimeConsumption(meterTypeId);
        return Result.data(result);
    }

    /**
     * 客户饼状图数据显示
     */
    @PermissionCheck
    @GetMapping("/getPieChartData")
    public String getPieChartData() {
        return Result.data(pointService.getPieChartData());
    }

    /**
     * 当前公司所属能源类型
     * @return String
     */
    @PermissionCheck
    @GetMapping("/getCompanyMeterType")
    public String getCompanyMeterType() {
        return Result.data(pointService.getCompanyMeterType());
    }

}
